/*
 * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
 * SPI Master library for arduino.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of either the GNU General Public License version 2
 * or the GNU Lesser General Public License version 2.1, both as
 * published by the Free Software Foundation.
 */

#include "SPI.h"
#include "core.h"

SPIClass SPI;

void SPIClass::begin()
{
    // Set direction register for SCK and MOSI pin.
    // MISO pin automatically overrides to INPUT.
    // When the SS pin is set as OUTPUT, it can be used as
    // a general purpose output port (it doesn't influence
    // SPI operations).

    pinMode(SCK, OUTPUT);
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(SS, OUTPUT);

    digitalWrite(SCK, LOW);
    digitalWrite(MOSI, LOW);
    digitalWrite(SS, HIGH);

    // Warning: if the SS pin ever becomes a LOW INPUT then SPI
    // automatically switches to Slave, so the data direction of
    // the SS pin MUST be kept as OUTPUT.
    SPCTL = SSIG | SPEN | MSTR;
    //SSIG: 1(Ignore SS)
    //SPEN: 1(Enable SPI)
    //DORD: 0(MSB)
    //MSTR: 1(Master)
    //CPIL/CPHA/SPR1/SPR0: 0000
    
    //Warning: According to STC12C56XXAD datasheet,
    //         when SSIG = 1 and CPHA = 0, the behavior is undefined.
    //         But we found it works fine in practices.
    //         The behavior is quite similar to ATmega328.
}

void SPIClass::end()
{
    SPCTL &= ~SPEN;
}

void SPIClass::setBitOrder(uint8_t bitOrder)
{
    if(bitOrder == LSBFIRST)
    {
        SPCTL |= DORD;
    }
    else
    {
        SPCTL &= ~DORD;
    }
}

void SPIClass::setDataMode(uint8_t mode)
{
    SPCTL = (SPCTL & ~SPI_MODE_MASK) | mode;
}

void SPIClass::setClockDivider(uint8_t rate)
{
    SPCTL = (SPCTL & ~SPI_CLOCK_MASK) | (rate & SPI_CLOCK_MASK);
}

